#include <iostream>
#include <string>
#include "utils/git_detector.h"
#include "core/submodule_rewriter.h"
#include "providers/gitee_provider.h"

void printUsage() {
    std::cout << "Usage: GitSubmoduleManager [repository_path] [--gitee-token TOKEN]" << std::endl;
    std::cout << "  repository_path: Path to Git repository (default: current directory)" << std::endl;
    std::cout << "  --gitee-token: Gitee personal access token for automatic mirror creation" << std::endl;
}

std::string getYesNoInput() {
    std::string answer;
    std::getline(std::cin, answer);
    return answer;
}

int main(int argc, char* argv[]) {
    std::string repo_path = ".";
    std::string gitee_token;
    
    // 处理命令行参数
    for (int i = 1; i < argc; i++) {
        std::string arg = argv[i];
        if (arg == "--help" || arg == "-h") {
            printUsage();
            return 0;
        } else if (arg == "--gitee-token" && i + 1 < argc) {
            gitee_token = argv[++i];
        } else if (arg.find("--") != 0) {
            repo_path = arg;
        }
    }
    
    std::cout << "🚀 Git Submodule Manager Starting..." << std::endl;
    std::cout << "📁 Repository: " << repo_path << std::endl;
    
    // 1. 检测 Git
    std::cout << "🔍 Detecting Git..." << std::endl;
    std::string git_path = GitDetector::findGitPath();
    if (git_path.empty()) {
        return 1;
    }
    
    std::cout << "📦 Using Git: " << git_path << std::endl;
    
    // 2. 创建子模块重写器
    SubmoduleRewriter rewriter(git_path);
    
    // 3. 加载指定目录的 .gitmodules
    std::cout << "📖 Loading .gitmodules..." << std::endl;
    if (rewriter.loadGitmodules(repo_path)) {
        std::cout << "✅ Successfully loaded .gitmodules" << std::endl;
        
        // 显示发现的子模块
        auto submodules = rewriter.getSubmodules();
        std::cout << "📋 Found " << submodules.size() << " submodules:" << std::endl;
        for (const auto& submodule : submodules) {
            std::cout << "  - " << submodule.path << " -> " << submodule.url << std::endl;
        }
        
        // 测试重写
        std::cout << "🔄 Checking for URL rewriting..." << std::endl;
        if (rewriter.rewriteToMirrors()) {
            std::cout << "🎯 Some URLs were rewritten to mirrors" << std::endl;
            
            // 如果提供了 Gitee token，尝试自动创建镜像仓库
            if (!gitee_token.empty()) {
                std::cout << "🔧 Attempting to create missing mirror repositories..." << std::endl;
                
                GiteeProvider gitee(gitee_token);
                int created_count = 0;
                int total_count = submodules.size();
                int current = 0;
                
                for (const auto& submodule : submodules) {
                    current++;
                    std::string target_url = submodule.url;
                    std::string repo_name = GiteeProvider::extractRepoNameFromUrl(target_url);
                    
                    std::cout << "[" << current << "/" << total_count << "] ";
                    
                    if (!repo_name.empty()) {
                        std::cout << "Checking: uesoft/" << repo_name << "... ";
                        std::cout.flush();
                        
                        if (!gitee.organizationRepositoryExists("uesoft", repo_name)) {
                            std::cout << "Creating... ";
                            std::cout.flush();
                            
                            if (gitee.createOrganizationRepository("uesoft", repo_name, "Mirror repository")) {
                                std::cout << "✅ Created" << std::endl;
                                created_count++;
                            } else {
                                std::cout << "❌ Failed" << std::endl;
                            }
                        } else {
                            std::cout << "✅ Already exists" << std::endl;
                        }
                    } else {
                        std::cout << "❌ Could not extract repo name from: " << target_url << std::endl;
                    }
                }
                
                std::cout << "📊 Summary: Created " << created_count << " new repositories" << std::endl;
            }
            
            // 询问是否应用更改
            std::cout << std::endl;
            std::cout << "💾 Apply changes to .gitmodules? (y/N): ";
            std::string answer = getYesNoInput();
            
            if (answer == "y" || answer == "Y") {
                std::cout << "💽 Applying changes to .gitmodules..." << std::endl;
                if (rewriter.applyChanges()) {
                    std::cout << "✅ Changes applied successfully!" << std::endl;
                    
                    if (gitee_token.empty()) {
                        std::cout << std::endl;
                        std::cout << "💡 Important: You need to manually create these repositories on Gitee:" << std::endl;
                        for (const auto& submodule : submodules) {
                            std::string repo_name = GiteeProvider::extractRepoNameFromUrl(submodule.url);
                            if (!repo_name.empty()) {
                                std::cout << "   - https://gitee.com/uesoft/" << repo_name << std::endl;
                            }
                        }
                    }
                } else {
                    std::cout << "❌ Failed to apply changes" << std::endl;
                }
            } else {
                std::cout << "ℹ️  Changes not applied" << std::endl;
            }
        } else {
            std::cout << "ℹ️  No URLs needed rewriting" << std::endl;
        }
    } else {
        std::cout << "❌ No .gitmodules found or parse error" << std::endl;
    }
    
    std::cout << std::endl;
    std::cout << "✨ Git Submodule Manager Finished" << std::endl;
    return 0;
}
